using ImageCSharp.Core.Interfaces;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using ImageCSharp.Core.Models;
using System;

namespace ImageCSharp.Core.Services
{
    /// <summary>
    /// 插件服务实现
    /// </summary>
    public class PluginService : IPluginService
    {
        private CompositionContainer? _container;
        private  ObservableCollection<IFilterPlugin> _filterPlugins = new();
        private  ObservableCollection<ISelectionPlugin> _selectionPlugins = new();
        private  ObservableCollection<IDrawingPlugin> _drawingPlugins = new();

        [ImportMany(typeof(IImagePlugin))]
        private IEnumerable<IImagePlugin>? _plugins;

        public void Initialize()
        {
            try
            {
                // 创建目录编录
                var catalog = new AggregateCatalog();

                // 添加当前程序集
                catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

                // 添加插件目录
                var pluginDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
                if (Directory.Exists(pluginDirectory))
                {
                    catalog.Catalogs.Add(new DirectoryCatalog(pluginDirectory));
                    Console.WriteLine($"Scanning plugins from: {pluginDirectory}");
                }
                else
                {
                    Console.WriteLine($"Plugins directory not found: {pluginDirectory}");
                }

                // 创建容器
                _container = new CompositionContainer(catalog);

                // 组合部件
                _container.ComposeParts(this);

                // 加载插件
                LoadPlugins();
                
                Console.WriteLine($"Plugin initialization completed. Found {_filterPlugins.Count} filters, {_selectionPlugins.Count} selections, {_drawingPlugins.Count} drawings");
            }
            catch (Exception ex)
            {
                // 记录错误但不中断应用程序
                Console.WriteLine($"Plugin initialization error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");
            }
        }

        public void LoadPlugins()
        {
            if (_plugins == null) return;

            foreach (var plugin in _plugins)
            {
                switch (plugin)
                {
                    case IFilterPlugin filterPlugin:
                        _filterPlugins.Add(filterPlugin);
                        break;

                    case ISelectionPlugin selectionPlugin:
                        _selectionPlugins.Add(selectionPlugin);
                        break;

                    case IDrawingPlugin drawingPlugin:
                        _drawingPlugins.Add(drawingPlugin);
                        break;
                }
            }
        }

        public ObservableCollection<IFilterPlugin> GetFilterPlugins()
        {
            return _filterPlugins;
        }

        public ObservableCollection<ISelectionPlugin> GetSelectionPlugins()
        {
            return _selectionPlugins;
        }

        public ObservableCollection<IDrawingPlugin> GetDrawingPlugins()
        {
            return _drawingPlugins;
        }

        public void ExecutePlugin(IImagePlugin plugin, ImageDocument document)
        {
            if (plugin == null || document?.Image == null)
                return;

            try
            {
                var processedImage = plugin.ProcessImage(document.Image);
                //document.Image = processedImage.Clone();
                document.Image = processedImage.CloneAs<Rgba32>();
                document.IsModified = true;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Error executing plugin {plugin.Name}: {ex.Message}", ex);
            }
        }
    }
}